<template>
  <div class="common-layout">
    <el-container>
      <el-aside :width="autowidth">
        <Aside :collapsed="collapsed"></Aside>
      </el-aside>
      <el-container>
        <el-header>
          <el-icon style="font-size: 30px;" @click="() => { collapsed = !collapsed }">
            <component :is="collapsed ? Expand : Fold"></component>
          </el-icon>
        </el-header>
        <el-main>
          <div class="tabs-container">
            <el-tabs v-model="tabStore.activeTab" type="card" @tab-click="handleTabClick" @tab-remove="handleTabRemove"
              class="demo-tabs">
              <el-tab-pane v-for="item in tabStore.tabList" :key="item.name" :label="item.title" :name="item.name"
                :closable="item.closable">
                
              </el-tab-pane>
            </el-tabs>
          </div>
          <router-view></router-view>
        </el-main>
        <el-footer>Footer</el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">

import { RouterView } from 'vue-router'
import Aside from '../components/Aside.vue'
// 引入icon组件
import { Expand, Fold } from '@element-plus/icons-vue'
import { ref, computed, watch } from 'vue'
import { useTabStore } from '@/store/tabStore.ts'
import { useRoute, useRouter } from 'vue-router'
// 定义菜单按钮收缩展开效果
const collapsed = ref<boolean>(false)

// 使用tab store
const tabStore = useTabStore()
const router = useRouter()
const route = useRoute()


const autowidth = computed(() => {
  if (collapsed.value) {
    return "64px"
  } else {
    return "200px"
  }
})


// 处理tab点击事件，激活tab
const handleTabClick = (tab: any) => {
  const targetTab = tabStore.tabList.find(item => item.name === tab.props.name)
  if (targetTab) {
    router.push(targetTab.path)
  }
}

// 处理tab关闭事件
const handleTabRemove = (tabName: string) => {
  tabStore.closeTab(tabName)
  // 关闭后跳转到当前激活的tab
  const activeTab = tabStore.tabList.find(item => item.name === tabStore.activeTab)
  if (activeTab) {
    router.push(activeTab.path)
  }
}

// 监听路由变化，自动添加tab
// 核心代码，监听路由。
watch(
  () => route.path,
  (newPath) => {
    const { name, meta } = route
    if (name && meta.title) {
      tabStore.addTab({
        //as 看作字符串
        title: meta.title as string,
        path: newPath,
        name: name as string,
        closable: name !== 'dashboard' // 首页不可关闭
      })
    }
  },
  { immediate: true }
)
</script>


<style scoped lang="less">
h3 {
  background-color: @menuBg;
}

.common-layout {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.el-container {
  height: 100%;
}

.el-header,
.el-footer {
  background-color: #B3C0D1;
  color: #333;
  // text-align: center;
  line-height: 80px;
}

.el-aside {
  background-color: @menuBg;
  color: #333;
  text-align: center;
  /* line-height: 200px; */
  overflow: hidden;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  /* line-height: 160px; */
}
</style>
